<?php
class Rabbit{
	var $conf;
	
	function Rabbit($conf){
		$this->conf = $conf;
	}
	
	function index(){
		$search_word = 'くらげ';
		$word	 	  = (array_key_exists('word',$_POST))? htmlspecialchars($_POST['word']):'';
		if(strcmp($word,'')==0){
			$word	 	  = (array_key_exists('word',$_GET))? htmlspecialchars($_GET['word']):'';
		}
		if(strcmp($word,'')==0){
			$word = $search_word;
		}
		
		$this->index_main($word);
	}
	
	function index_main(){
		//初期表示用 検索文字列

		$BASE_URL	  = 'http://nicosb.orz.hm/';
		$codebase	  = 'http://tubesb.ddo.jp/';
		$mail		  = 'nicosb@nakayoshi.cc';
		$password	  = 'nicosbnicosb';

		$rows = '';
		$contents = @file_get_contents('http://www.youtube.com/rss/tag/'.urlencode($word).'.rss');
			
		$xml = @simplexml_load_string($contents);
		if($xml){
			$row_search   = array('[[MAIL]]','[[PASSWORD]]','[[ID]]','[[IMG]]','[[TITLE]]','[[MAX_FILE_CNT]]','[[BASE_URL]]','[[DISPID]]','[[OBJECT]]');
			$row_template = file_get_contents("template/row.html");
			
			$object_search   = array('[[CODEBASE]]','[[MAIL]]','[[PASSWORD]]','[[ID]]','[[IMG]]','[[TITLE]]','[[MAX_FILE_CNT]]','[[BASE_URL]]','[[DISPID]]');
			$object_template = file_get_contents("template/object.html");
			
			$cnt = 1;
			//foreach ($xml->movie as $movie) {
			foreach ($xml->channel->item as $movie) {
				$enclosure_attrs = $movie->enclosure->attributes();
				//imgのurlを抽出
				$img_url = '';
				$matchs = array();
				$ret = preg_match("/src=\"([^\"]+)\"/",$movie->description,$matchs);
				if($ret!==false){
					$img_url = $matchs['1'];
				}
				
				//movieidを正規表現で抽出
				$matchs = array();
				//$ret = preg_match("/movieid=([^&]+)/",$movie->link,$matchs);
				$ret = preg_match("/v=(.*)/",$movie->link,$matchs);
				if($ret!==false){
					//IDは、youtube_??????
					$id = 'youtube_'.$matchs[1];
					$img = $img_url;
					$title = $movie->title;
					$max_file_cnt = Common::getFileCnt($id);
					$dispid = $matchs[1];
					
					$object = '';
					//[ToDo] キャッシュリクエスト用のリンクを表示するように変更するべき。
					//if($max_file_cnt>0){
						$object_replace = array($codebase,$mail,$password,$id,$img,$title,$max_file_cnt,$BASE_URL,$dispid);
						$object = str_replace($object_search,$object_replace,$object_template);
					//}
					
					//[ToDo] テスト期間だけ 自動キャッシュ
					//http://nicosb.orz.hm/api/cache.php?sm_id=[動画ID]
					//$contents = @file_get_contents('http://nicosb.orz.hm/api/cache.php?sm_id='.$id);
					
					//タグ置き換え
					$row_replace = array($mail,$password,$id,$img,$title,$max_file_cnt,$BASE_URL,$dispid,$object);
					$rows .= str_replace($row_search,$row_replace,$row_template);
					
					$cnt++;
					if($cnt>10) break;
				}
			}
		}

		$search  = array('[[ROWS]]','[[MAIL]]','[[PASSWORD]]','[[WORD]]');
		$replace = array($rows,$mail,$password,$word);
		$template = file_get_contents("template/index.html");
		$html = str_replace($search,$replace,$template);

		//画面出力
		header('Content-type: text/html; charset=UTF-8');
		echo $html;
	}
	
	function nicosb_index(){
		$mail		  = '';
		$password	  = '';
		$word	 	  = '';
		$type	  	  = '';
			
		if(array_key_exists('word',$_POST)){
			$mail		  = (array_key_exists('mail',$_POST))? htmlspecialchars($_POST['mail']):'';
			$password	  = (array_key_exists('password',$_POST))? htmlspecialchars($_POST['password']):'';
			$word	 	  = (array_key_exists('word',$_POST))? htmlspecialchars($_POST['word']):'';
			$type	  	  = (array_key_exists('type',$_POST))? htmlspecialchars($_POST['type']):'';
		}
		else{
			//GET
			$word	 	  = (array_key_exists('word',$_GET))? htmlspecialchars($_GET['word']):'';
			if(strcmp($word,'')!=0) $type = '0';
		}
		
		//クッキーからmail,passwordを読み込む
		if((strcmp($mail,'')==0) && (strcmp($password,'')==0)){
			$mail		  = (array_key_exists('mail',$_COOKIE))? htmlspecialchars($_COOKIE['mail']):'nicosb@nakayoshi.cc';
			$password	  = (array_key_exists('password',$_COOKIE))? htmlspecialchars($_COOKIE['password']):'nicosbnicosb';
		}
		
		$this->nicosb_main($mail,$password,$word,$type);
	}
	
	function nicosb_main($mail,$password,$word,$type){
		$BASE_URL	  = 'http://nicosb.orz.hm/';
		$codebase	  = 'http://tubesb.ddo.jp/';
		
		if(strcmp($type,'0')==0){
			$type0 = 'selected="selected"';
			$type1 = '';
		}
		else if(strcmp($type,'1')==0){
			$type0 = '';
			$type1 = 'selected="selected"';
		}
		
		$cnt = 20;
		$rows = '';
		if((strcmp($mail,'')!=0) && (strcmp($password,'')!=0)){
			
			//クッキーにmail,passwordを保存
			setcookie("mail", $mail, time()+3600);
			setcookie("password", $password, time()+3600);
			
			$xml = false;
			
			$cacheOptions = array (
				'cacheDir' => '',
				'fileLocking' => true,
				'lifeTime' => 300,
				'writeControl' => true,
				'automaticSerialization' => true,
				'automaticCleaningFactor' => 200,
				'hashedDirectoryLevel' => 1,
				'cacheDir'=>'C:/work/php/nicosb/server/cache/cache_lite/'
			);
			
			$cache_lite = new Cache_Lite($cacheOptions);
			
			if(strcmp($word,'')==0){
				//ランキング
				$xmlname = 'mexa_ranking_all.xml';
				$contents_url = 'http://nicosb.orz.hm/api/ranking_all.php?mail='.urlencode($mail).'&password='.urlencode($password);
			}
			else{
				if(strcmp($type,'')!=0){
					//検索
					$xmlname = 'mexa_search_'.urlencode($word).'_'.$type.'.xml';
					$contents_url = 'http://nicosb.orz.hm/api/search.php?mail='.urlencode($mail).'&password='.urlencode($password).'&type='.$type.'&word='.urlencode($word);

					//tagcloud
					$this->addTags($word);
						
				}
			}
			
			if(!($contents = $cache_lite->get($xmlname))){
				//TODO ラインキングＸＭＬを読み込んで一覧を生成する
				$contents = @file_get_contents($contents_url);
				//キャッシュへ保存
				if($contents){
					$cache_lite->save( $contents );
				}
			}

			if(strcmp($contents,'')!=0){
				$xml = @simplexml_load_string($contents);
				if($xml){
					$row_search   = array('[[MAIL]]','[[PASSWORD]]','[[ID]]','[[IMG]]','[[TITLE]]','[[MAX_FILE_CNT]]','[[BASE_URL]]','[[DISPID]]','[[OBJECT]]');
					$row_template = file_get_contents("template/nicosb_row.html");
					
					$object_search   = array('[[CODEBASE]]','[[MAIL]]','[[PASSWORD]]','[[ID]]','[[IMG]]','[[TITLE]]','[[MAX_FILE_CNT]]','[[BASE_URL]]','[[DISPID]]');
					$object_template = file_get_contents("template/object.html");
					
					foreach ($xml->movie as $movie) {
						$id = $movie->id;
						$img = $movie->img;
						$title = $movie->title;
						$max_file_cnt = $movie->max_file_cnt;
						$dispid = $movie->id;

						$object_replace = array($codebase,$mail,$password,$id,$img,$title,$max_file_cnt,$BASE_URL,$dispid);
						$object = str_replace($object_search,$object_replace,$object_template);
						
						//タグ置き換え
						$row_replace = array($mail,$password,$id,$img,$title,$max_file_cnt,$BASE_URL,$dispid,$object);
						$rows .= str_replace($row_search,$row_replace,$row_template);
						
						$cnt--;
						if($cnt<=0) break;
					}
				}
			}
		}

		{
			//ニコニコ市場
			$affiliate_id = 'niconicoichiba06-22';
			$search  = array('[[TITLE]]','[[LINK]]','[[DESCRIPTION]]','[[PUBDATE]]');
			$template = file_get_contents('template/nicosb_ichiba_row.html');
			$nicoichiba = '';
			$ichiba = Common::nicoichiba(2);
			foreach ($ichiba as $item) {
				
				$itemid = str_replace('http://ichiba.nicovideo.jp/item/','',$item->link);
				$type = substr($itemid,0,2);
				if(strcmp($type,'az')!=0){
					//yahoo 等
					$link  = 'http://m.nicovideo.jp/ichiba_go.php?itemid='.$itemid.'&from=ranking&&cp_in=ichiba_rk';
				}
				else{
					//amazon
					$asin = substr($itemid,2);
					$link = 'http://www.amazon.co.jp/exec/obidos/ASIN/'.$asin.'/'.$affiliate_id.'/ref=nosim';
				}
				
				//niconicoichiba-22
				$description = $item->description;
				//if(5 == rand(1,10)){
				$description = str_replace('niconicoichiba-22',$affiliate_id,$item->description);
				//}
				
				$replace = array($item->title,$link,$description,$item->pubdate);
				$nicoichiba .= str_replace($search,$replace,$template);
			}
		}
		
		$tagcloud = $this->tagcloud();
		{
			//index
			$search  = array('[[ROWS]]','[[MAIL]]','[[PASSWORD]]','[[WORD]]','[[TYPE0]]','[[TYPE1]]','[[NICOICHIBA]]','[[TAGCLOUD]]');
			$replace = array($rows,$mail,$password,$word,$type0,$type1,$nicoichiba,$tagcloud);
			$template = file_get_contents('template/nicosb_index.html');
			$html = str_replace($search,$replace,$template);

			//画面出力
			header('Content-type: text/html; charset=UTF-8');
			echo $html;
		}
	}
	
	function addTags($word){
		$count = 50;
		$tagcloud = array();
		$path = dirname(__FILE__).'/cache/tagcloud';
		if(file_exists($path)){
			$contents = file_get_contents($path);
			$tagcloud = unserialize($contents);
		}
		
		//保存してあるタグの数をチェック
		$tc = count($tagcloud);
		if($tc>$count){
			$a = $tc-$count;
			for($i=0;$i<$a;$i++){
				unset($tagcloud[$i]);
			}
		}
		
		$word = mb_convert_kana($word,'s','UTF-8');
		
		$tmps = split(' ',$word);
		if($tmps){
			//すでに登録してあった場合削除
			foreach ($tmps as $v) {
				$key = array_search($v,$tagcloud);
				if($key !== false){
					unset($tagcloud[$key]);
				}
			}
			
			foreach ($tmps as $v) {
				$v = trim($v);
				if(strcmp($v,'')!=0){
					$tagcloud[] = $v;
				}
			}
		}
		else{
			$key = array_search(trim($tmps),$tagcloud);
			if($key !== false){
				unset($tagcloud[$key]);
			}
			$tagcloud[] = trim($tmps);
		}
		
		//ソートして添え字を付け直し
		ksort($tagcloud,SORT_NUMERIC);
		$tagcloud = array_values($tagcloud);
		
		//シリアライズして保存
		$contents = serialize($tagcloud);
		file_put_contents($path,$contents);
	}
	
	function tagcloud(){
		$ret   = '';
		$count = 10;
		
		$tagcloud = array();
		$path = dirname(__FILE__).'/cache/tagcloud';
		if(file_exists($path)){
			$contents = file_get_contents($path);
			$tagcloud = unserialize($contents);
		}
		
		if(is_array($tagcloud)){
			krsort($tagcloud,SORT_NUMERIC);
			foreach ($tagcloud as $key => $tag) {
				$size = 8;
				$ret .= '<span style="font-size:'.$size.'px">'
						.'<a href="nicosb.php?word='.urlencode($tag).'">'
						.$tag
						.'</a>'
						//.'('.$key.')'
						.'</span>'
						."\r\n";
				$count--;
				if($count<=0) break;
			}
		}
		return $ret;
	}
	
	function page(){
		$sm_id = (array_key_exists('sm_id',$_GET))? htmlspecialchars($_GET['sm_id']):'';
		if(strcmp($sm_id,"")==0) {
			header('Location: http://nicosb.orz.hm/public/');
			exit;
		}
		
		if(strpos($sm_id,'youtube_')!==false){
			$sm_id = str_replace(array('youtube_'),array(''),$sm_id);
			$this->index_main($sm_id);
		}
		else{
			$mail = 'nicosb@nakayoshi.cc';
			$password = 'nicosbnicosb';
			$this->nicosb_main($mail,$password,$sm_id,'1');
		}

	}
}